package com.example.yangxu0703.thundermapclient.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.callback.StringResultCallback;
import com.example.yangxu0703.thundermapclient.fragment.DirectinfoFragment;
import com.example.yangxu0703.thundermapclient.fragment.MapDirectionFragment;
import com.example.yangxu0703.thundermapclient.fragment.RouteFragment;
import com.example.yangxu0703.thundermapclient.util.Util;
import com.thundersoft.mm.phone.ConnectionManager;

import org.json.JSONObject;

import java.util.Timer;


public class MainActivity extends BaseActivity implements View.OnClickListener, StringResultCallback {

    private Fragment[] listfragment;
    private RelativeLayout radioGroup;
    private Button map, meida, user;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    public static int choose;
    public MapDirectionFragment mapDirectionFragment;
    private int Current_fragment = 0;
    private boolean isFourStart;

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    radioGroup.setVisibility(View.GONE);
                    listfragment[3] = new RouteFragment();
                    transaction = manager.beginTransaction();
                    transaction.add(R.id.fragment_direct, listfragment[3]);
                    transaction.hide(listfragment[0]).hide(listfragment[3]).show(listfragment[3]).commit();
                    ((RouteFragment) listfragment[3]).handler.sendEmptyMessage(1);
                    Current_fragment = 3;
                    break;
                case 3:
                    Log.i("start direction ", "start");
                    choose = msg.arg2;
                    listfragment[4] = new MapDirectionFragment();
                    mapDirectionFragment = (MapDirectionFragment) listfragment[4];
                    //设置数据监听
                    mapDirectionFragment.setCallback(MainActivity.this);

                    transaction = manager.beginTransaction();
                    transaction.add(R.id.fragment_direct, listfragment[4]);
                    /* transaction.remove(fragments[6]);*/
                    transaction.hide(listfragment[0]).hide(listfragment[3]).hide(listfragment[4]);
                    transaction.show(listfragment[4]).commit();
                    Current_fragment = 4;
                    isFourStart = true;
                    break;
                case 4:
                    transaction = manager.beginTransaction();
                    transaction.hide(listfragment[0]).hide(listfragment[3]).hide(listfragment[4]);
                    transaction.show(listfragment[3]).commit();
                    listfragment[4].onDestroy();
                    listfragment[4] = null;
                    ConnectionManager.sendDriveMessage(null);
                    Current_fragment = 3;
                    break;
                case 5:
                    try {
                        ConnectionManager.btTextMsgListener.sendMsg("hearts".getBytes());
                    }catch (Exception e){}
                    handler.sendEmptyMessageDelayed(5,2000);
                    break;
                case 6:
                    startOtherThing();
                    break;
            }

        }


    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(Util.isFirstBoot(MainActivity.this)){
            if (Build.VERSION.SDK_INT >= 23) {
                this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.BLUETOOTH, Manifest.permission.RECEIVE_SMS,
                        Manifest.permission.READ_SMS, Manifest.permission.CALL_PHONE,
                        Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_CONTACTS,
                        Manifest.permission.GET_ACCOUNTS}, 001);
            }else {
                startOtherThing();
            }
        }else {
                startOtherThing();
        }
       /* com.au.bt.demo.App.BT_NAME = "BULL";
        com.au.bt.demo.App.init(getApplication());
        com.au.bt.demo.App.handler.sendEmptyMessage(0);*/
       handler.sendEmptyMessageDelayed(5,2000);


    }

    private void startOtherThing() {
        listfragment = new Fragment[5];
        initView();
        initfragment();
        ConnectionManager.init(getApplicationContext());
    }


    private void initfragment() {
        manager = getSupportFragmentManager();
        listfragment[0] = new DirectinfoFragment();
        transaction = manager.beginTransaction();
        transaction.add(R.id.fragment_direct, listfragment[0]);
       /* listfragment[0] = manager.findFragmentById(R.id.map_locationFragement);
        transaction = manager.beginTransaction();*/
        transaction.hide(listfragment[0]).show(listfragment[0]).commit();
    }


    private void initView() {
        radioGroup = findViewById(R.id.botton_bar);
        map = findViewById(R.id.map_direct);
        meida = findViewById(R.id.media_center);
        user = findViewById(R.id.user_center);
        map.setOnClickListener(this);
        meida.setOnClickListener(this);
        user.setOnClickListener(this);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 001) {
            /*for (int i=0;i<grantResults.length;i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "授权失败！", Toast.LENGTH_SHORT).show();
                    MainActivity.this.requestPermissions(new String[]{},100);
                }
            }*/
            if (grantResults[3]==PackageManager.PERMISSION_GRANTED){
                handler.sendEmptyMessage(6);
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.map_direct:
                Intent meidaIntent = new Intent(MainActivity.this, MediaCenterActivity.class);
                startActivity(meidaIntent);
                break;
            case R.id.media_center:
                /* transaction.show(listfragment[0]).commit();*/
                /*transaction = manager.beginTransaction();
                transaction.hide(listfragment[0]).hide(listfragment[3]);
                transaction.show(listfragment[0]).commit();*/
                break;
            case R.id.user_center:
                /* transaction.show(listfragment[2]).commit();*/
                Intent userIntent = new Intent(MainActivity.this, UserCenterActivity.class);
                startActivity(userIntent);

                break;
        }
    }

    @Override
    public void onBackPressed() {
        Log.i("Current-onBackPressed", "" + Current_fragment);
        //返回键处理
        if (Current_fragment == 3) {
            transaction = manager.beginTransaction();
            transaction.hide(listfragment[0]).hide(listfragment[3]);
            transaction.show(listfragment[0]).commit();
            radioGroup.setVisibility(View.VISIBLE);
            ((DirectinfoFragment) listfragment[0]).naviView.setVisibility(View.VISIBLE);
            ((DirectinfoFragment) listfragment[0]).resetMap();
            ;
            listfragment[3].onDestroy();
            listfragment[3] = null;
            Current_fragment = 0;
        } else if (Current_fragment == 4) {
            transaction = manager.beginTransaction();
            transaction.hide(listfragment[0]).hide(listfragment[3]).hide(listfragment[4]);
            transaction.show(listfragment[3]).commit();
            listfragment[4].onDestroy();
            listfragment[4] = null;
            ConnectionManager.sendDriveMessage(null);
            Current_fragment = 3;
        } else if (Current_fragment == 0) {
            super.onBackPressed();
        }
    }


    @Override
    public void stringcallback(String s) {
        String[] temp = s.split("<>");
        if (!temp[1].isEmpty()) {
            //调用接口回调数据
            ConnectionManager.sendDriveMessage(temp[1]);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ConnectionManager.release();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
